/*
 * Copyright 2012 yura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.opu.pc.security;

import org.opu.pc.domain.SystemSettingsManagement;
import org.opu.pc.domain.SystemSettingsManagement.DefaultAuthenticationOption;
import static org.opu.pc.domain.SystemSettingsManagement.DefaultAuthenticationOption.SystemUserCredentials;
import static org.opu.pc.domain.SystemSettingsManagement.Option.DefaultAuthentication;
import org.opu.pc.domain.UserManagement;
import org.opu.pc.domain.domains.security.User;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 *
 * @author yura
 */
public class SystemAccountPreAuthUserDetailsService extends GuestPreAuthUserDetailsService {
    
    public SystemAccountPreAuthUserDetailsService(
            SystemSettingsManagement settingsManagement, 
            UserManagement userManagement) {
        super(settingsManagement, userManagement);
    }

    @Override
    public UserDetails loadUserDetails(Authentication token) 
            throws UsernameNotFoundException {

        if (token != null && token.getPrincipal() != null
                && !"SystemAccountAuthentication".equals(token.getPrincipal())){
            throw new BadCredentialsException("Not SystemAccount principal");
        }
        
        DefaultAuthenticationOption defaultAuth = settingsManagement
                .getDefaultAuthenticationOption(DefaultAuthentication);
        
        if (available && defaultAuth == SystemUserCredentials) {
            String account = getSystemAccount();
            User user = userManagement.getNotGuestUserByName(account);
            if (user == null){
                throw new UsernameNotFoundException("User " + account + " not found.");
            }
            return new UserDetailsData(user);
        }
        
        throw new UsernameNotFoundException("Authentication with system user account is unavailable");
    }

    public String getSystemAccount() {
        return System.getProperty("user.name");
    }
    
}
